package cannot.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cannot.model.ModelTv;
import cannot.pojo.MainType;
import cannot.pojo.OtherType;
import cannot.pojo.Tv;
import cannot.pojo.TypeTv;
import cannot.service.MainTypeService;
import cannot.service.OtherTypeService;
import cannot.service.TvService;
import cannot.service.TypeTvService;
import cannot.service.UserService;
import cannot.shiro.ShiroUtil;
import cannot.util.FileUtil;
import cannot.util.ImageUtil;
import cannot.util.StoragePlace;


@Controller
public class TvController {
	String imgPath =StoragePlace.basicPlace+"img"+File.separator;
	String videoPath = StoragePlace.basicPlace+"tv"+File.separator;
	@Autowired
	OtherTypeService otherTypeService;
	@Autowired
	TvService tvService;
	@Autowired
	TypeTvService typeTvService;
	@Autowired
	MainTypeService mainTypeService;
	@Autowired
	UserService userService;

	
	 /**
     * 投稿管理→视频投稿
     * @return
     */
    @RequestMapping("/rightContent_subTv")
    public String rightContentSubTv(){
    	 return "user/rightContent/subTv";
    }
    
    /**
     * 影视信息→影视上传(管理员页面)
     */
    @RequestMapping("/admin_rightContent_subTv")
    public String rightAdminContentSubTv(Model model){
    	List<MainType> mainTypes = mainTypeService.listMainType();
    	model.addAttribute("mainTypes", mainTypes);
    	 return "admin/rightContent/subTv";
    }
	
	/**
	 * 用户数据tv的提交操作
	 */
	@RequestMapping(method = RequestMethod.POST, path = "/admin_addTv")
	@Transactional(rollbackFor = { Exception.class })
	@ResponseBody
    public String addTv(@RequestBody ModelTv modelTv) {
		//获取用户id
    	String userName =  ShiroUtil.getUserByPrincipal();
    	if(userName==null){
    		return "LOGIN";
    	}else{
    		long uid = userService.getByName(userName).getId();
			Tv tv = modelTv.getTv();
			List<Integer> ids = modelTv.getIds();
			tv.setUploader_id((int)uid);
			//增加tv
			tvService.insert(tv);
			//获取tv的返回id，将类型号加进去
			for(Integer i:ids){
				TypeTv typeTv = new TypeTv();
				typeTv.setTv_id(tv.getId());
				typeTv.setType_id(i);
				typeTvService.insert(typeTv);
			}
	    	 return "SUCCESS";
    	}
    }
	
	int i = 0;
	/**
	 * 添加视频时传输视频，
	 * @param videoFile
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, path = "/admin_uploadTv")
	@ResponseBody
    public String upload(@RequestPart("file") MultipartFile videoFile,@RequestParam(value="chunk",required=false)Integer chunk,@RequestParam(value="chunks",required=false)Integer chunks) {
		System.err.println("chunks为"+chunks);
		String fileName = videoFile.getOriginalFilename();
		String prefix=fileName.substring(fileName.lastIndexOf("."));
    	 //如果没有分片
    	 if(chunks==null||chunks==0){
    		 String pictureName = UUID.randomUUID().toString() + prefix;
    		 try {
    			 File file = new File(videoPath);
    			 file.mkdirs();
    			 videoFile.transferTo(new File(file +File.separator+ pictureName));
    		 } catch (Exception e) {
    		 }
    		 return pictureName;
    	 }else{
    		 i++;
    		 //存储传入文件，命名方式为videoPath+chunk+文件名
    		 String filePathThis = videoPath+chunk+prefix;
    		 System.err.println("文件名为"+chunk);
    		 System.err.println("i为"+i);
    		 File fileThis = new File(filePathThis);
    		 FileOutputStream fos = null;
    		 String pictureName =null;
    		 try{
    			 fos= new FileOutputStream(fileThis);
        		 byte[] bytes  = videoFile.getBytes();
        		 fos.write(bytes);
        		 fos.close();
        		//当文件发送完毕，进行拼接，并删除chunk文件
                 if(chunks == i){
                	 pictureName = UUID.randomUUID().toString() + prefix;
                	 File f = new File(videoPath+pictureName);
                	 FileOutputStream fos1 = new FileOutputStream(f,true);
                	 for(int j=0;j<i;j++){
                		 File f1 = new File(videoPath+j+prefix);
                		 FileInputStream fis = new FileInputStream(f1);
                		 byte[] byte2 = new byte[(int)f1.length()];
                		 fis.read(byte2);
                		 fis.close();
                		 f1.delete();
                		 fos1.write(byte2);
                	 }
                	 fos1.close();
                	 i=0;
                	 return pictureName;
                 }
    		 }catch(Exception e){
    			 e.printStackTrace();
    			 i=0;
    		 }
    		 System.err.println("返回的影片串为："+pictureName);
    		 return pictureName;
    	 }
    }
	
	/**
	 * 添加图片时传输图片，位置在c盘下tv/img目录中
	 * @param picture
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, path = "/admin_uploadTvPicture")
	@ResponseBody
    public String uploadPicture(HttpServletRequest req,@RequestPart("file") MultipartFile picture) {
    	  String pictureName = UUID.randomUUID().toString() + ".jpg";
          try {
              File file = new File(imgPath);
              file.mkdirs();
              File f = new File(imgPath+ pictureName);
              picture.transferTo(f);
              ImageUtil.resizeImage(f, 180, 240, f);
          } catch (Exception e) {
          }
          return pictureName;
    }
	/**
	 * 获取图片，定位到服务器资源
	 */
   /* @RequestMapping("virtual_img")
    public void renderPicture(String pictureId, HttpServletResponse response) {
        String path =imgPath+ pictureId;
        try {
            byte[] bytes = FileUtil.toByteArray(path);
            response.getOutputStream().write(bytes);
        }catch (Exception e){
            //如果找不到图片就返回一个默认图片
            try {
                response.sendRedirect("img/uploadPic.png");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }*/
    
    /**
     * 根据用户选择的类型选择不同的分区,如果isfilm为Y，则返回3的查询值，如果为N，则返回2的查询值
     */
    @RequestMapping("isfilm_type")
    @ResponseBody
    public Object selectIsFilmType(@RequestParam("isfilm") String isfilm){
    	List<OtherType> lis  = new ArrayList<OtherType>();
    	if(isfilm.equals("Y")){
    		lis = otherTypeService.listByMainType(3);
    	}else if(isfilm.equals("N")){
    		lis = otherTypeService.listByMainType(2);
    	}
    	return lis;
    }
    
    
    /**
     * 根据选择的主类型切换
     */
    @RequestMapping("admin_isfilm_type")
    @ResponseBody
    public Object selectAdminFilmType(@RequestParam("isfilm") Integer isfilm){
    	List<OtherType> lis  = otherTypeService.listByMainType(isfilm);
    	return lis;
    }
   /* *
    @RequestMapping("playTv")
	public void playTv(Integer id,HttpServletResponse response){
		//通过id找到播放的url
		Tv tv = tvService.selectById(id);
		String path =videoPath+ tv.getVideo_url();
		File f = new File(path);
		try(FileInputStream fis = new FileInputStream(f);
				BufferedInputStream bis = new BufferedInputStream(fis)) {
			
			while(true){
				System.err.println("传输数据");
				byte[] bytes = new byte[(int) Math.pow(2,26)];
				bis.read(bytes);
				response.getOutputStream().write(bytes);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
   */
}
